package com.example.KeHuDuan;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.client.SocketClient;
import com.google.gson.JsonArray;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import gson.Test.Main;
import gson.Test.MediaList;
import gson.Test.Messages;
import gson.Test.Music;
import gson.Test.Video;
import gson.client.InstructionList;
import gson.client.Params;

import static gson.Test.Main.getMusicList;
import static gson.Test.Main.getVideoList;
import static gson.client.InstructionList.DATA_OP.GET_LIST;
import static gson.client.InstructionList.MODE.MODE_MUSIC;
import static gson.client.InstructionList.MODE.MODE_VIDEO;
import static gson.client.InstructionList.ORDER.ORDER_BACK;
import static gson.client.InstructionList.ORDER.ORDER_CONTINUE;
import static gson.client.InstructionList.ORDER.ORDER_NEXT;
import static gson.client.InstructionList.ORDER.ORDER_PAUSE;
import static gson.client.InstructionList.ORDER.ORDER_PLAY;
import static gson.client.InstructionList.ORDER.ORDER_PREVIOUS;

public class MediaService extends Service {
    public List<Music> musicList = new ArrayList<>();
    public List<Video> videoList = new ArrayList<>();
    private static final String TAG = "ClientMediaService";

    private boolean IsConnectedWIFI = true;
    SocketClient socketClient;  //SocketClient类

    private int currentMediaIndex;

    protected Handler mHandlerMedia;

    public class MediaBinder extends Binder {
        //可在活动中调用的pulic void方法
        public void sendHandler(Handler handler) {
            mHandlerMedia = handler;
        }

        public void destroyHandler(Handler handler) {
            mHandlerMedia = null;
        }




        //客户端socket连接
        public void connect() {
            if (!socketClient.isAvailable()) {
                socketClient.value(MediaService.this, getHotPotIp(), 34569);
                socketClient.openClientThread();
                //连接成功,弹出Toast消息
                Log.d(TAG, "连接成功,通过判断WiFi得到local IP：" + getLocalIp() +
                        "热点的IP：" + getHotPotIp());
            } else {
                Toast.makeText(MediaService.this, "已连接！", Toast.LENGTH_SHORT).show();
            }


        }

        public void test() {
            socketClient.sendMsg2("我是Client");
        }

        //发送socketClient
        public SocketClient sendSocket() {
            return socketClient;
        }


        //客户端，发送音乐播放命令（3）
        public String sMusicContinue() {
            String str = Main.sendOrder(ORDER_CONTINUE, MODE_MUSIC, null, 0);
            socketClient.sendMsg2(str);
            Log.d("音乐控制", "sMusicPlay: 播放");
            Log.d(TAG, "音乐播放的字符串： " + str);
            return str;
        }

        //客户端，发送视频播放命令（3）(3)
        public String sVideoContinue() {
            String str = Main.sendOrder(ORDER_CONTINUE, MODE_VIDEO, null, 0);
            socketClient.sendMsg2(str);
            Log.d(TAG, "视频播放的字符串： " + str);
            return str;
        }

        public String sMusicPlay(int position){
            String str = Main.sendOrder(ORDER_PLAY, MODE_MUSIC, null, position );
            socketClient.sendMsg2(str);
            Log.d(TAG, "sMusicPlay: send onClick position order" + position);
            return str;
        }

        public String sVideoPlay(int position){
            String str = Main.sendOrder(ORDER_PLAY, MODE_VIDEO, null, position );
            socketClient.sendMsg2(str);
            Log.d(TAG, "sVideoPlay: send onClick position order" + position);
            return str;
        }

        //客户端，发送音乐暂停命令（4）
        public void sMusicPause() {
            String str = Main.sendOrder(ORDER_PAUSE, MODE_MUSIC, null, 0);
            socketClient.sendMsg2(str);
            Log.d("音乐控制", "sMusicPause:暂停 ");
            Log.d(TAG, "音乐暂停的字符串： " + str);
        }

        //客户端，发送视频暂停命令（4）（4）
        public void sVideoPause() {
            String str = Main.sendOrder(ORDER_PAUSE, MODE_VIDEO, null, 0);
            socketClient.sendMsg2(str);

            Log.d(TAG, "音乐暂停的字符串： " + str);
        }


        //客户端，发送音乐列表上一个命令（5）
        public void sMusicPrevious() {
            String str = Main.sendOrder(ORDER_PREVIOUS, MODE_MUSIC, null, 0);
            socketClient.sendMsg2(str);
            Log.d(TAG, "音乐上一首的字符串： " + str);
        }

        //客户端，发送视频列表上一个命令（5）(5)
        public void sVideoPrevious() {
            String str = Main.sendOrder(ORDER_PREVIOUS, MODE_VIDEO, null, 0);
            socketClient.sendMsg2(str);
            Log.d(TAG, "视频上一首的字符串： " + str);
        }

        //客户端，发送音乐下一个命令（6）
        public void sMusicNext() {
            String str = Main.sendOrder(ORDER_NEXT, MODE_MUSIC, null, 0);
            socketClient.sendMsg2(str);
            Log.d(TAG, "音乐下一首的字符串： " + str);
        }

        //客户端，发送视频下一个命令（6）
        public void sVideoNext() {
            String str = Main.sendOrder(ORDER_NEXT, MODE_VIDEO, null, 0);
            socketClient.sendMsg2(str);
            Log.d(TAG, "视频下一首的字符串： " + str);
        }

        //客户端，发送得到音乐列表命令（10），，，，，服务端解析收到命令后再发送（2）
        public void sGetMusicList(int start_no, int page_size) {
            Params params = new Params();
            params.addParam(InstructionList.PARAM.START_NO, start_no);
            params.addParam(InstructionList.PARAM.PAGE_SIZE, page_size);
            String str = Main.sendOrder(GET_LIST, MODE_MUSIC, params);
            socketClient.sendMsg2(str);
            Log.d(TAG, "发送要得到音乐列表的字符串： " + str);
        }

        //客户端，发送得到视频列表命令（11），，，，，服务端解析收到命令后再发送（1）
        public void sGetVideoList(int start_no, int page_size) {
            Params params = new Params();
            params.addParam(InstructionList.PARAM.START_NO, start_no);
            params.addParam(InstructionList.PARAM.PAGE_SIZE, page_size);
            String str = Main.sendOrder(GET_LIST, MODE_VIDEO, params);
            socketClient.sendMsg2(str);
            Log.d(TAG, "发送要得到视频列表的字符串： " + str);
        }



        public void stop(){
            String str = Main.sendOrder(ORDER_BACK, 0, null, 0);
            socketClient.sendMsg2(str);
        }


    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: ");
        createNotificationChannel();
        SocketClient.ClientHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull android.os.Message msg) {
               switch (msg.what) {
                   case SocketClient.RETURN_MESSAGE:
                       checkMessages(msg);
                      break;
                  case SocketClient.DISCONNECT:
                      notifyDisconnect();
                      break;
                  case SocketClient.CONNECT_ERROR:
                      notifyConnectError();
                      break;
               }

            }
        };
        initSocket();
        super.onCreate();
    }

    private void createNotificationChannel() {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 通知渠道的id
        String id = this.getPackageName();
        // 用户可以看到的通知渠道的名字.
        CharSequence name = this.getClass().getSimpleName();
//         用户可以看到的通知渠道的描述
        String description = name.toString();
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
//         配置通知渠道的属性
        mChannel.setDescription(description);
//         设置通知出现时的闪灯（如果 android 设备支持的话）
        mChannel.enableLights(true); mChannel.setLightColor(Color.RED);
//         设置通知出现时的震动（如果 android 设备支持的话）
//        mChannel.enableVibration(true);
//        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
//         最后在notificationmanager中创建该通知渠道 //
        mNotificationManager.createNotificationChannel(mChannel);

        // 为该通知设置一个id
        int notifyID = 1;
        // 通知渠道的id
        String CHANNEL_ID = "my_channel_01";
        // Create a notification and set the notification channel.
        Notification notification = new Notification.Builder(this, id)
                .setContentTitle("New Message") .setContentText("You've received new messages.")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build();
        startForeground(1,notification);
    }

    private void initSocket() {
        socketClient = new SocketClient();
    }

    //解析列表信息并操作
    public void recvListMessage(Messages messages) {
        System.out.println(messages.getResult() + "-----");
        MediaList mediaList = new MediaList();

        Log.d(TAG, "recvListMessage" + messages.getMsg().length());

        JsonArray ja = MediaList.parseJson(mediaList, messages.getMsg());
        if (mediaList.mType == MediaList.MEDIA_TYPE_MUSIC) {
            Log.d("Main", "音乐ListView适配器 ");
            //可以在此处设置音乐ListView适配器
//                message = new Message();
//                message.what = InstructionList.PARAM.LIST_MUSIC;
//                message.obj = musicList;
//                mHandlerMedia.sendMessage(message);

            //getMusicList(ja);  	//此方法返回List<Music>
            musicList = getMusicList(ja);
        } else {
            Log.d("Main", "视频ListView适配器 ");
            //可以在此处设置视频ListView适配器
            videoList = getVideoList(ja);    //此方法返回List<Video>
        }

        if (mHandlerMedia != null) {
           Message msg = mHandlerMedia.obtainMessage(GET_LIST);
           msg.obj = mediaList.mType == MediaList.MEDIA_TYPE_MUSIC ? musicList : videoList;
           mHandlerMedia.sendMessage(msg);
        }
    }

    private void checkMessages(Message msg) {
        try {
            String str = new String((byte[]) msg.obj, "UTF-8");
            Messages messages = Messages.parseJson(str);
            switch (messages.getOrder()) {
                case GET_LIST:
                    recvListMessage(messages);
                    break;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void notifyDisconnect() {
        Toast.makeText(MediaService.this, "连接断开！", Toast.LENGTH_SHORT).show();
    }

    private void notifyConnectError() {
        Toast.makeText(MediaService.this, "连接失败！", Toast.LENGTH_SHORT).show();
    }

    public MediaService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MediaBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    //本地机子IP
    private String getLocalIp() {
        // 获取wifi服务
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        // 判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        Log.i("得到WiFi热点名称(赵赵）", wifiInfo.getSSID());
        Log.d("ip", String.valueOf(ipAddress));
        String ip = intToIp(ipAddress);
        Log.d("通过判断WiFi得到的本端ipipip", ip);
        return ip;
    }

    //开热点的机子的IP
    private String getHotPotIp() {
        // 获取wifi服务
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        // 判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
        Log.i("热点：", String.valueOf(dhcpInfo.serverAddress));
        String ip2 = intToIp(dhcpInfo.serverAddress);
        Log.d("热点ipipip", ip2);
        return ip2;
    }

    private String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + (i >> 24 & 0xFF);
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        if (socketClient != null) {
            socketClient.close();
        }
        super.onDestroy();
    }
}
